#include <unistd.h>
#include <pthread.h>
#include <vector>
#include <string>
#include <iostream>
#include "lockguard.hpp"
using namespace std;
#define NUM 4
int ticket = 10;
class threadData
{
public:
    threadData(int number)
    {
        threadname = "thread-> " + to_string(number);
    }
    std::string threadname;
    pthread_mutex_t *lock; // 保存锁
};
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *getticket(void *arg)
{
    threadData *td = static_cast<threadData *>(arg);
    while (true)
    {
        {
            LockGuard lg(&mutex);
            if (ticket > 0)
            {
                usleep(1000000);
                std::cout << td->threadname << " get " << ticket << std::endl;
                ticket--;
            }
            else
            {
                std::cout << td->threadname << " break" << std::endl;
                break;
            }
        }
        usleep(1000000);
    }
    return NULL;
}
void* test(void*arg)
{
    threadData *td = static_cast<threadData *>(arg);
    pthread_mutex_lock(&mutex);
    std::cout << td->threadname <<" get one lock"<< std::endl;
    pthread_mutex_lock(&mutex);
    std::cout << td->threadname << " get two lock" << std::endl;  
    return NULL;
}
int main()
{
    std::vector<pthread_t> vp1;
    std::vector<threadData *> td1;
    pthread_mutex_t lock;
    pthread_mutex_init(&lock, nullptr);
    for (int i = 0; i < 1; i++)
    {
        pthread_t tid;
        threadData *td = new threadData(i);
        td->lock = &lock;
        td1.push_back(td);
        pthread_create(&tid, NULL, test, td);
        vp1.push_back(tid);
    }
    sleep(5);
    pthread_mutex_unlock(&mutex);
    for (int i = 0; i < vp1.size(); i++)
    {
        pthread_join(vp1[i], NULL);
    }
    for (auto e : td1)
    {
        delete e;
    }

    return 0;
}